package com.ming.multifunction.mq;

import com.ming.multifunction.common.ErrorCode;
import com.ming.multifunction.contant.BiMqConstant;
import com.ming.multifunction.contant.CommonConstant;
import com.ming.multifunction.exception.BusinessException;
import com.ming.multifunction.exception.ThrowUtils;
import com.ming.multifunction.manager.AiManager;
import com.ming.multifunction.model.domain.Chart;
import com.ming.multifunction.service.ChartService;
import com.ming.multifunction.utils.ExcelUtils;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.stereotype.Component;
import retrofit2.http.Header;

import javax.annotation.Resource;

@Slf4j
@Component
public class BiMessageConsumer {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private AiManager aiManager;
    @Resource
    private ChartService chartService;

    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMsg(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if ( chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NULL_ERROR,"图表为空");
        }
        //调用AI
        String result = aiManager.doChat(CommonConstant.BI_MODEL_ID, buildUserInput(chart));
        String[] splits = result.split("【【【【【");
        if (splits.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        chart.setGenChart(genChart);
        chart.setGetResult(genResult);
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult){
            channel.basicNack(deliveryTag, false, false);
//            throw new BusinessException(ErrorCode.NULL_ERROR,"图表为空");
            return;
        }
        log.info("receiveMsg message={}", message);
        channel.basicAck(deliveryTag, false);

    }

    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();
        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        // 压缩后的数据
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }

}
